import os
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from flask import Flask, render_template
from pyspark.sql import SparkSession
import requests

# 配置数据库连接参数
jdbc_url = "jdbc:mysql://8.130.77.210:3306/mydatabase"
properties = {
    "user": "root",
    "password": "Oyyc020801",
    "driver": "com.mysql.cj.jdbc.Driver"
}

# 创建 Flask 应用
app = Flask(__name__)

# 创建 static 目录用于保存生成的图片
if not os.path.exists('static'):
    os.makedirs('static')

def generate_images():
    spark = SparkSession.builder \
        .appName("MySQL to PySpark") \
        .config("spark.jars", "/root/spark/jars/mysql-connector-j-8.0.33.jar") \
        .getOrCreate()

    # 读取数据库表格
    df = spark.read.jdbc(url=jdbc_url, table="mysql", properties=properties)
    df = df.toPandas()

    # 生成发文数量直方图
    plt.figure()
    df['articles_count'].hist(bins=50, range=(0, 400))
    plt.title('Articles Count')
    plt.xlabel('Articles Count')
    plt.ylabel('Frequency')
    plt.xlim(0, 400)
    plt.savefig('static/articles_count.png')

    # 生成回答问题数量直方图
    plt.figure()
    df['answer_count'].hist(bins=50, range=(0, 400))
    plt.title('Answer Count')
    plt.xlabel('Answer Count')
    plt.ylabel('Frequency')
    plt.xlim(0, 400)
    plt.savefig('static/answer_count.png')

    # 生成性别的饼状图
    plt.figure()
    df['gender'].value_counts().plot.pie(autopct='%1.1f%%')
    plt.title('Gender Distribution')
    plt.savefig('static/gender_distribution.png')

    # 绘制姓名中姓的词云图
    name_text = ' '.join(df['name'])
    wordcloud = WordCloud(width=800, height=400, background_color='white').generate(name_text)
    plt.figure(figsize=(10, 6))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.title('Word Cloud of Names')
    plt.savefig('static/name_wordcloud.png')  # 保存词云图

@app.route('/')
def index():
    generate_images()
    return render_template('测试.html')

if __name__ == '__main__':
    port = 5200
    host = '0.0.0.0'

    try:
        # 获取公网 IP
        public_ip = requests.get('https://api.ipify.org').text
        print(f" * Running on http://{public_ip}:{port}")
    except requests.RequestException as e:
        print(f"Failed to get public IP: {e}")

    # 关闭 Flask 的默认打印信息
    import logging
    log = logging.getLogger('werkzeug')
    log.disabled = True

    # 启动 Flask 应用并添加自定义打印信息
    app.run(debug=True, host=host, port=port, use_reloader=False)
    print(f" * Running on http://{public_ip}:{port} (Press CTRL+C to quit)")